class WebSocketClient {
    constructor(url,autoReconnect=false,autoHeartbeatCheck=false,reconnectInterval=5000,heartbeatInterval=3000) {
        this.url = url;  // 服务器的接口地址
        this.socket = null; // 客户端websocket实例
        this.autoReconnect = autoReconnect; // 自动重连标识
        this.reconnectInterval = reconnectInterval; // 重连间隔时间，单位为毫秒
        this.autoHeartbeatCheck = autoHeartbeatCheck; // 是否开启心跳检测
        this.heartbeatInterval = heartbeatInterval; // 心跳检测间隔时间，单位为毫秒

        this.onOpen = () => {};
        this.onClose = () => {};
        this.onMessage = () => {};
        this.onError = () => {};

        this.connect();
    }

    connect() {
        // WebSocket浏览器兼容性判断
        if (typeof window.WebSocket === "function") {
            this.socket = new WebSocket(this.url);
        } else {
            console.log("WebSocket is not supported by your browser.");
        }

        this.socket.onopen = () => {
            this.onOpen();
            if(this.autoHeartbeatCheck){
                this.startHeartbeat();
            }
        };

        this.socket.onclose = (event) => {
            this.onClose(event);
            if(this.autoHeartbeatCheck){
                this.stopHeartbeat(); // 客户端断开连接后关闭心跳检测的定时器
            }
            if (this.autoReconnect) {  // 是否自动重连
                setTimeout(() => {
                    this.connect();
                }, this.reconnectInterval);
            }
        };

        this.socket.onmessage = (event) => {
            this.onMessage(event);
        };

        this.socket.onerror = (error) => {
            this.onError(error);
        };
    }

    send(data) {
        if (this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(data);
        }
    }

    disconnect() {
        this.autoReconnect = false;
        this.socket.close();
    }

    // 每隔3s心跳检测一次（客户端向服务端发送ping）
    startHeartbeat() {
        this.heartbeatTimer = setInterval(() => {
            if (this.socket.readyState === WebSocket.OPEN) {
                this.socket.send('ping');
            }
        }, this.heartbeatInterval);
    }

    stopHeartbeat() {
        clearInterval(this.heartbeatTimer);
    }
}

export default WebSocketClient;